package com.ajmd.onlineexam.baseUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * 人脸识别接口封装
 * @author ajmd
 * @since 2023/3/16 18:03
 */
public class FacePlusPlusUtils {
    //Face++ 应用API Key
    public static final String API_KEY="ADm4Md8bjBzqer9MD_f2ff-_BLF78NWW";
    //Face++ 应用API Secret
    public static final String API_SECRET="5X0L0TaiCOJWdVTfiLEV_IAUnfi4Du87";
    //Face++ 人脸比对API请求地址
    private static final String FACEPLUS_API_URL = "https://api-cn.faceplusplus.com/facepp/v3/compare";

    public static float faceCompare(String imageBase641, String img2Path) throws IOException {
        //准备请求参数
        Map<String, String> params = new HashMap<String, String>();
        params.put("api_key", API_KEY);
        params.put("api_secret", API_SECRET);
        //将两张图片转换为Base64编码，并拼接请求参数
        String imageBase642 = fileToBase64(new File(img2Path));
        params.put("image_base64_1", imageBase641);
        params.put("image_base64_2", imageBase642);

        //发送HTTP请求并获取返回结果
        String resultStr = sendPostRequest(FACEPLUS_API_URL, params);

        //解析JSON格式的返回结果，获取人脸相似度得分
        JSONObject jsonObj = JSONObject.parseObject(resultStr);
        String similarity = jsonObj.getString("confidence");
        return Float.parseFloat(similarity);
    }
    /**
     * 将指定文件转换成Base64编码的字符串
     * @param file 要转换的文件
     * @return Base64编码的字符串
     * @throws IOException
     */
    private static String fileToBase64(File file) throws IOException {
        byte[] data = FileUtils.readFileToByteArray(file);
        return Base64.encodeBase64String(data);
    }

    /**
     * 发送HTTP POST请求
     *
     * @param urlStr
     * @param params
     * @return
     * @throws IOException
     */
    private static String sendPostRequest(String urlStr, Map<String, String> params) throws IOException {
        String boundary = "----" + System.currentTimeMillis(); // 分隔符
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(5000); // 设置连接超时时间
        conn.setReadTimeout(5000); // 设置读取超时时间
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String name = entry.getKey();
                String value = entry.getValue();
                dos.writeBytes("--" + boundary + "\r\n");
                dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n");
                dos.writeBytes(value + "\r\n");
            }
        }
        dos.writeBytes("--" + boundary + "--" + "\r\n");
        dos.flush();

        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        }
        return "";
    }
}
